﻿package  {
	
	import flash.display.BitmapData;
	import flash.display.DisplayObjectContainer;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	public class TCollisionDetector {
		
		private var _returnValue: Boolean;
		
		private var _onePoint: Point;
		private var _twoPoint: Point;
		
		private var _oneRectangle: Rectangle;
		private var _twoRectangle: Rectangle;
		
		private var _oneClipBmpData: BitmapData;
		private var _twoClipBmpData: BitmapData;
		
		private var _oneOffset: Matrix;
		private var _twoOffset: Matrix;
		

		public function TCollisionDetector() {
			// constructor code
		}
		
		public function Destroy() {
			_onePoint = null;
			_twoPoint = null;
			_oneRectangle = null;
			_twoRectangle = null;
			_oneClipBmpData = null;
			_twoClipBmpData = null;
			_oneOffset = null;
			_twoOffset = null;
		}
		
		public function HitTest(Arg1: TObject, Arg2: TObject): Boolean {
			_returnValue = false;
			
			_twoRectangle = Arg1.getBounds(Arg1);
			_oneOffset = Arg1.transform.matrix;
			_oneOffset.tx = Arg1.x - Arg2.x;
			_oneOffset.ty = Arg1.y - Arg2.y;	
			
			_twoClipBmpData = new BitmapData(_twoRectangle.width, _twoRectangle.height, true, 0);
			_twoClipBmpData.draw(Arg1, _oneOffset);		
			
			_oneRectangle = Arg2.getBounds(Arg2);
			_oneClipBmpData = new BitmapData(_oneRectangle.width, _oneRectangle.height, true, 0);
			
			_twoOffset = Arg2.transform.matrix;
			_twoOffset.tx = Arg2.x - Arg2.x;
			_twoOffset.ty = Arg2.y - Arg2.y;	
			
			_oneClipBmpData.draw(Arg2, _twoOffset);
			
			_onePoint = new Point(_oneRectangle.x, _oneRectangle.y);
			_twoPoint = new Point(_twoRectangle.x, _twoRectangle.y);
			
			if (GetDistance(GetCenter(Arg1), GetCenter(Arg2)) < (Arg1.width + Arg2.width)) {
				if (_oneClipBmpData.hitTest(_onePoint, 255, _twoClipBmpData, _twoPoint, 255)) {
					_returnValue = true;
				}
			}
			
			_twoClipBmpData.dispose();
			_oneClipBmpData.dispose();
			
			return _returnValue;
			
			Destroy();
		}
		
		public function GetDistance(arg1: Point, arg2: Point): Number {
			var n1 = (arg1.x - arg2.x) * (arg1.x - arg2.x);
			var n2 = (arg1.y - arg2.y) * (arg1.y - arg2.y);
			var Result = Math.sqrt(n1 + n2);
			
			if (Result < 0) {
				Result = Result * -1;
			}
			
			return Result;
		}
		
		public function GetCenter(arg: TObject): Point {
			var X: Number = (arg.x * 2 + arg.width) / 2;
			var Y: Number = (arg.y * 2 + arg.height) / 2;
			return new Point(X, Y);
		}

	}
	
}
